import os
import dotenv
from flask import Flask
from loguru import logger
import schedule
from functools import partial
from threading import Thread
import time

from .models import db
from .routes import register_routes
from .plots import register_plot_routes
from .prepare_plot_data import update_plot_data

# 加载环境变量
dotenv.load_dotenv()

# 获取当前文件所在目录的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
# 构造指向前端资源的绝对路径
frontend_dist_path = os.path.join(current_dir, "..", "frontend", "dist")

# 创建Flask应用
app = Flask(__name__, static_folder=frontend_dist_path, static_url_path="")

# 配置日志
logger.add("app.log", rotation="500 MB", level="INFO")
logger.info("===Starting the application...===")

# 确保 instance 文件夹存在
instance_path = os.path.join(current_dir, "..", "instance")
instance_path = os.path.abspath(instance_path)
os.makedirs(instance_path, exist_ok=True)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(
    instance_path, "cards.db"
)
app.config["SQLALCHEMY_BINDS"] = {
    "reviews": "sqlite:///"
    + os.path.join(instance_path, "review_logs.db")  # 第二个数据库
}
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# 初始化数据库
db.init_app(app)

# 注册路由
register_routes(app)
register_plot_routes(app)

os.makedirs("instance", exist_ok=True)  # 自动创建instance目录

with app.app_context():
    db.create_all()  # 自动创建所有数据库表

# 定义调度线程变量
schedule_thread = None


def init_scheduler():
    """初始化调度器"""
    global schedule_thread

    schedule.every().day.at("23:00").do(
        partial(update_plot_data, os.path.join(instance_path, "plot_data.json"), app)
    )

    def run_schedule():
        while True:
            schedule.run_pending()
            time.sleep(1)

    # 创建并启动调度线程，设置为守护线程
    schedule_thread = Thread(target=run_schedule, daemon=True)
    schedule_thread.start()
    logger.info("调度器已启动")


def stop_scheduler():
    """停止调度器"""
    global schedule_thread
    if schedule_thread and schedule_thread.is_alive():
        # 对于守护线程，我们不需要特殊处理，它会随主程序退出而自动结束
        logger.info("调度器已停止")
